package com.aso114.project.mvp.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.base.BaseApplication;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.commonview.NoticeDialog;
import com.aso114.project.commonview.RoundImageView;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Base64Coder;
import com.aso114.project.util.Helper;
import com.aso114.project.util.SystemBarHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人信息
 */
public class PersonDataActivity extends BaseSimpleActivity {
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    @BindView(R.id.layout_title_bar_right_tv)
    TextView layoutTitleBarRightTv;
    Intent intent;
    @BindView(R.id.logout)
    TextView logout;
    @BindView(R.id.imghead)
    RelativeLayout imghead;
    @BindView(R.id.userInfo_name)
    TextView userInfoName;
    @BindView(R.id.nickname)
    RelativeLayout nickname;
    @BindView(R.id.userInfo_phone)
    TextView userInfoPhone;
    @BindView(R.id.tellphone)
    RelativeLayout tellphone;
    @BindView(R.id.userInfo_head)
    ImageView userInfoHead;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;

    private RequestOptions mRequestOptions;

    @Override
    protected int getResouseId() {
        return R.layout.persondata;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, titleTopLy);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
        layoutTitleBarTitleTv.setText("设 置");
        mRequestOptions = RequestOptions.circleCropTransform()
                .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                .skipMemoryCache(true);//不做内存缓存
        if (!TextUtils.isEmpty(LoginSP.getInstance().getUserName())) {
            userInfoName.setText(LoginSP.getInstance().getUserName());
        }
        if (!TextUtils.isEmpty(LoginSP.getInstance().getUserMobile())) {
            userInfoPhone.setText(LoginSP.getInstance().getUserMobile());
        }
        if (!TextUtils.isEmpty(LoginSP.getInstance().getUserLitpic())) {
            Glide.with(PersonDataActivity.this).load(LoginSP.getInstance().getUserLitpic()).apply(mRequestOptions.placeholder(R.mipmap.my_touxiang_c).error(R.mipmap.my_touxiang_c)).into(userInfoHead);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(LoginSP.getInstance().getUserName())) {
            userInfoName.setText(LoginSP.getInstance().getUserName());
        }
        if (!TextUtils.isEmpty(LoginSP.getInstance().getUserMobile())) {
            userInfoPhone.setText(LoginSP.getInstance().getUserMobile());
        }
    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_title_bar_back_iv, R.id.layout_title_bar_title_tv, R.id.logout, R.id.nickname, R.id.imghead})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_title_bar_back_iv:
                finish();
                break;

            case R.id.nickname:  // 名字
                intent = new Intent(PersonDataActivity.this, ChangeNickActivity.class);
                startActivity(intent);

                break;
            case R.id.logout:
                new NoticeDialog(PersonDataActivity.this, "确定要退出账号吗?", "", "确定", new NoticeDialog.NoticeOnClick() {
                    @Override
                    public void onclick() {
                        LoginSP.getInstance().setToken("");
                        LoginSP.getInstance().setUserAreaId("");
                        LoginSP.getInstance().setUserEmail("");
                        LoginSP.getInstance().setUserLitpic("");
                        LoginSP.getInstance().setUserMobile("");
                        LoginSP.getInstance().setUserName("");
                        LoginSP.getInstance().setCityname("");
                        finish();

                        Intent intent = new Intent(PersonDataActivity.this, LoginActivity.class);
                        startActivity(intent);

                    }
                }).show();

                break;

            case R.id.imghead: //  头像
                showChooseHeadDialog();
                break;
        }
    }

    public void showChooseHeadDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_select_pic, null, false);
        final Dialog dialog = new Dialog(this, R.style.popupWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        // 设置点击外围解散
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        //进入系统相册

        Button btnFromCamera = (Button) view.findViewById(R.id.btn_camera);
        btnFromCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 相机
                PictureSelector.create(PersonDataActivity.this)
                        .openCamera(PictureMimeType.ofImage())
                        .enableCrop(true)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .withAspectRatio(1, 1)
                        .rotateEnabled(false)// 裁剪是否可旋转图片 true or false
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .cropCompressQuality(100)// 裁剪压缩质量 默认90 int
                        .cropWH(100, 100)// 裁剪宽高
                        .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                        .synOrAsy(true)
                        .showCropFrame(false)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                dialog.dismiss();
            }
        });
        Button btnFromPhoto = (Button) view.findViewById(R.id.btn_gallery);
        btnFromPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //相册
                PictureSelector.create(PersonDataActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .enableCrop(true)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .withAspectRatio(1, 1)
                        .rotateEnabled(false)// 裁剪是否可旋转图片 true or false
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .cropCompressQuality(100)// 裁剪压缩质量 默认90 int
                        .cropWH(100, 100)// 裁剪宽高
                        .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                        .synOrAsy(true)
                        .showCropFrame(false)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                dialog.dismiss();
            }
        });
        Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    String path = null;
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    if (selectList.get(0).isCompressed()) {
                        path = selectList.get(0).getCompressPath();
                    }
                    if (TextUtils.isEmpty(path)) {
                        Helper.showToast("图片加载失败");
                        return;
                    }
                    Log.i("yxp", path);
                    final String finalPath = path;
                    CommentModel.getInstant().setUserInfo(fileToBase64(finalPath), "", new CallBack() {
                        @Override
                        public void onSuccess(Object o, boolean isSuccess, String msg) {
                            Helper.gotoLogin(isSuccess);//token失效去重新登陆
                            Glide.with(PersonDataActivity.this).load(finalPath).apply(mRequestOptions.placeholder(R.mipmap.my_touxiang_c).error(R.mipmap.my_touxiang_c)).into(userInfoHead);
                        }

                        @Override
                        public void onFailure(String fail) {

                        }
                    });
                    break;
            }
        }
    }

    public static String fileToBase64(String path) {
        byte[] bytes = getBytes(path);
        return Base64Coder.encodeLines(bytes);
    }

    public static byte[] getBytes(String filePath) {
        File file = new File(filePath);
        ByteArrayOutputStream out = null;
        try {
            FileInputStream in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) != -1) {

                out.write(b, 0, b.length);
            }
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] s = out.toByteArray();
        return s;

    }

}
